package fightplan.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import fightplan.business.Category;
import fightplan.business.Tournament;
import fightplan.core.FPExceptionHandler;
import fightplan.persistence.WinnerReport;
import fightplan.views.MainView;

@SuppressWarnings("serial")
public class WinnerReportAction extends AbstractAction {

	private MainView mainView;

	public WinnerReportAction(MainView mainView) {
		super("Rangliste exportieren");
		this.mainView = mainView;
	}

	public void actionPerformed(ActionEvent actionEvent) {
		List<Category> selectedCategories = mainView.getSelectedCategories();

		if (selectedCategories != null) {
			Object[] possibleValues = { "Alle", "Selektierte" };
			Object selectedValue = JOptionPane.showInputDialog(null,
					"Sollen alle oder nur selektierte\nKategorien ausgegeben werden?", "Export",
					JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[0]);

			if (selectedValue == null)
				return;
			if ("Alle".equals(selectedValue))
				selectedCategories = null;
		}

		if (selectedCategories == null) {
			Tournament tournament = (Tournament) mainView.getTournament().getValue();
			selectedCategories = tournament.getCategories();
		}

		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setCurrentDirectory(new File("."));
		fileChooser.setDialogTitle("Name des Ranglistenreports");
		fileChooser.setName("report.xls");
		fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
			public boolean accept(File f) {
				return !f.isFile() || f.getName().endsWith(".xls");
			}

			public String getDescription() {
				return "*.xls (Excelfile)";
			}
		});
		if (fileChooser.showDialog(mainView, "Speichern") == JFileChooser.APPROVE_OPTION) {
			try {
				WinnerReport.createReport(selectedCategories, fileChooser.getSelectedFile());
			} catch (FileNotFoundException fnne) {
				FPExceptionHandler
						.instance()
						.showWarning(
								"Report konnte nicht geschrieben werden. Ev. ist dieses File in Excel schon geöffnet.\nIn dem Fall einen anderen Name wählen oder das File in Excel schliessen.",
								"Export fehlgeschlagen");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}